package com.youkeda.test.http;

import okhttp3.Call;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author xshuai
 */
public class FormPoster {
    public static void main(String[] args) {
        String url = "http://tcc.taobao.com/cc/json/mobile_tel_segment.htm";
        Map<String, String> formData = new HashMap<String, String>();
        formData.put("tel", "18603761952");
        FormPoster poster = new FormPoster();
        String content = poster.postContent(url, formData);
        System.out.println("API调用结果");
        System.out.println(content);
    }

    public String postContent(String url, Map<String, String> formData) {
        OkHttpClient okHttpClient = new OkHttpClient();
        FormBody.Builder builder = new FormBody.Builder();
        for (String key : formData.keySet()) {
            builder.add(key, formData.get(key));
        }
        FormBody formBody = builder.build();
        Request request = new Request.Builder().
                url(url).post(formBody).build();
        Call call = okHttpClient.newCall(request);
        String result = null;
        try {
            result = call.execute().body().string();
        } catch (IOException e) {
            System.out.println("request " + url + "error .");
            e.printStackTrace();
        }
        return result;
    }
}
